<template>
    <div class="img" id="materialFile">
      <a-upload name="file" :multiple="isMultiple" :action="uploadParams.actionUrl" :headers="uploadParams.headers"
        :data="formKeyData" :fileList="fileList" :beforeUpload="beforeUpload" :disabled="disabled" :remove="handleRemove" @change="handleChange" @preview="handlePreview">
        <a-button>选择文件 </a-button>
      </a-upload>
    </div>
  </template>
  
  <script>
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { getFileAccessHttpUrl } from '@/api/manage'
  import { uploadToken } from '@/api/api'
  
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10)
  }
  const getFileName = path => {
    if (path.lastIndexOf('\\') >= 0) {
      let reg = new RegExp('\\\\', 'g')
      path = path.replace(reg, '/')
    }
    return path.substring(path.lastIndexOf('/') + 1)
  }
  export default {
    name: 'JImageUpload',
    data() {
      return {
        uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
        uploadLoading: false,
        picUrl: false,
        headers: {},
        fileList: [],
        previewImage: '',
        previewVisible: false,
        token: '',
        formKeyData: {
          token: '',
          key: ''
        },
        uploadHost: this.uploadParams.uploadHost
      }
    },
    props: {
      text: {
        type: String,
        required: false,
        default: '上传'
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: 'temp'
      },
      value: {
        type: [String, Array],
        required: false
      },
      disabled: {
        type: Boolean,
        required: false,
        default: false
      },
      isMultiple: {
        type: Boolean,
        required: false,
        default: false
      },
      //update-begin-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
      number: {
        type: Number,
        required: false,
        default: 0
      },
      //update-end-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
      uploadParams: {
        type: Object,
        default: null,
        required: false
      },
      // update date：20220905 for:上传视频时，必须使用该属性，接受值：video/*
      accept: {
        type: String,
        required: false,
        default: 'image/*'
      },
      fileSize: {
        type: Number,
        required: false,
        default: 2
      }
    },
    watch: {
      // value: {
      //   handler(val, oldValue) {
      //     if (val instanceof Array) {
      //       this.initFileList(val.join(','))
      //     } else {
      //       this.initFileList(val)
      //     }
      //     if (!val || val.length == 0) {
      //       this.picUrl = false
      //     }
      //   },
      //   //立刻执行handler
      //   immediate: true
      // }
    },
    created() {
      this.fetchUploadToken()
    },
    methods: {
      fetchUploadToken() {
        uploadToken().then(res => {
          if (res.code == 0) {
            this.token = res.data
          } else {
            this.$message.warning(res.msg)
          }
        })
      },
      initFileList(paths) {
        if (!paths || paths.length == 0) {
          this.fileList = []
          return
        }
        this.picUrl = true
        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          let url = getFileAccessHttpUrl(arr[a])
          fileList.push({
            url: url,
            uid: url,
            name: getFileName(arr[a]),
            status: 'done',
            thumbUrl: this.accept == 'video/*' ? url + '?vframe/jpg/offset/1' : url // update date：20220905 for:上传视频时回显第一帧
            // uid: uidGenerator(),
            // name: getFileName(arr[a]),
            // status: 'done',
            // url: url,
            // response: {
            //   status: 'history',
            //   message: arr[a]
            // }
          })
        }
        this.fileList = fileList
        this.$emit('fileChange1', this.fileList)
        console.log(this.fileList)
      },
      beforeUpload: function (file) {
        new Promise((resolve, reject) => {
          const key = new Date().getTime()
          // 支持批量多张上传
          this.formKeyData = {
            key: key,   // 非必填项，批量上传时不能使用相同key，会导致614报错；不指定key，七牛默认将文件hash作为文件名保存
            token: this.token
          }
          // return isJpgOrPng && isLt2M
          resolve(file)
        })
      },
      handleChange(info) {
        let fileList = []
        if (this.isMultiple) {
          fileList = [...info.fileList]
        } else {
          fileList = info.fileList.length > 0 ? [info.fileList[info.fileList.length - 1]] : []
        }
        if (fileList.length > this.number && this.isMultiple) {
          this.$message.warning('最多上传' + this.number + '张！')
          return false
          // fileList = fileList.slice(-this.number)
        }
        if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else if (info.file.status === 'done') {
          let list = fileList.map(file => {
            if (file.response) {
              file.url = this.uploadHost + file.response.key
              // update date：20220905 for:上传视频时回显第一帧
              if (this.accept == 'video/*') {
                file.thumbUrl = this.uploadHost + file.response.key + '?vframe/jpg/offset/1'
              }
            }
            return file
          })
          this.fileList = list
          // console.log(this.fileList)
          this.$emit('fileChange1', this.fileList)
        }
  
        // update-date:20220701 for:important!!必须设置fileList，否则只会调用一次并且状态为uploading
        this.fileList = [...fileList]
        // update-date:20220701 for:important!!必须设置fileList，否则只会调用一次并且状态为uploading
  
        /*
          if (info.file.status === 'done' || info.file.status === 'removed') {
            this.handlePathChange()
          } */
      },
      handleRemove(file) {
        const index = this.fileList.indexOf(file)
        const newFileList = this.fileList.slice()
        newFileList.splice(index, 1)
        this.fileList = newFileList
        this.$emit('fileChange1', this.fileList)
      },
      // 预览
      handlePreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      getAvatarView() {
        if (this.fileList.length > 0) {
          let url = this.fileList[0].url
          return getFileAccessHttpUrl(url)
        }
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = []
        if (!this.isMultiple && uploadFiles.length > 0) {
          arr.push(uploadFiles[uploadFiles.length - 1].response.message)
        } else {
          for (let a = 0; a < uploadFiles.length; a++) {
            // update-begin-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
            if (uploadFiles[a].status === 'done') {
              arr.push(uploadFiles[a].response.message)
            } else {
              return
            }
            // update-end-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
          }
        }
        if (arr.length > 0) {
          path = arr.join(',')
        }
        this.$emit('change', path)
      },
      handleDelete(file) {
        //如有需要新增 删除逻辑
        console.log(file)
      },
      handleCancel() {
        this.close()
        this.previewVisible = false
      },
      close() { }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
  </script>
  
  <style scoped>
  /* update--end--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白*/
  
  /deep/ .image-upload-single-over .ant-upload-select {
    /* display: none; */
  }
  </style>
  <style>
  #materialFile .ant-upload-list {
    margin-left: -100px;
  }
  </style>
  